package com.sgj.mvcframework.servlet;

import com.sgj.mvcframework.annotation.ShenAutowired;
import com.sgj.mvcframework.annotation.ShenController;
import com.sgj.mvcframework.annotation.ShenRequestMapping;
import com.sgj.mvcframework.annotation.ShenService;
import com.sgj.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * 控制器
 * @author 沈国纪
 * @date 2021/12/17 23:36
 */
public class ShenDispatcherServlet extends HttpServlet {

	private Properties properties = new Properties();
	/**
	 * 缓存扫描到的类的全限定类名
	 */
	private List<String> classNames = new ArrayList<>();
	/**
	 * ioc容器
	 */
	private Map<String, Object> ioc = new HashMap<>();
	/**
	 * handleMapping
	 */
	private Map<String, Handler> handlerMapping = new HashMap<>();

	@Override
	public void init(ServletConfig config) throws ServletException {
		// 1、加载配置文件 springmvc.properties
		String contextConfigLocation = config.getInitParameter("contextConfigLocation");
		doLoadConfig(contextConfigLocation);

		// 2、扫描相关的类，扫描注解
		doScan(properties.getProperty("scanPackage"));

		// 3、初始化bean对象（实现Ioc容器，基于注解）
		doInstance();

		// 4、实现依赖注入
		doAutoWried();

		// 5、构造一个handleMapping处理器映射器，将配置好的url和Handler建立映射关系
		initHandleMapping();
		System.out.println("mvc 初始化完成");

		// 6、等待请求进入处理请求
	}

	/**
	 * 构造映射器
	 */
	private void initHandleMapping() {
		if (ioc.isEmpty()) {
			return;
		}
		for (Map.Entry<String, Object> entry : ioc.entrySet()) {
			// 获取ioc中当前遍历的对象的class类型
			Class<?> aClass = entry.getValue().getClass();
			if (!aClass.isAnnotationPresent(ShenController.class)) {
				continue;
			}
			String baseUrl = "";
			if (aClass.isAnnotationPresent(ShenRequestMapping.class)) {
				ShenRequestMapping annotation = aClass.getAnnotation(ShenRequestMapping.class);
				baseUrl = annotation.value();
			}
			// 获取方法
			Method[] methods = aClass.getMethods();
			for (int i = 0; i < methods.length; i++) {
				Method method = methods[i];
				if (!method.isAnnotationPresent(ShenRequestMapping.class)) {
					continue;
				}
				ShenRequestMapping annotation = method.getAnnotation(ShenRequestMapping.class);
				String methodUrl = annotation.value();
				String url = baseUrl + methodUrl;

				Handler handler = new Handler(entry.getValue(), method, url);

				// 计算方法的参数位置信息
				Parameter[] parameters = method.getParameters();
				for (int j = 0; j < parameters.length; j++) {
					Parameter parameter = parameters[j];
					if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
						handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
					} else {
						handler.getParamIndexMapping().put(parameter.getName(), j);
					}
				}
				// 建立url和Handler的映射关系
				handlerMapping.put(url, handler);
			}
		}
	}

	/**
	 * 实现依赖注入
	 */
	private void doAutoWried() {
		if (ioc.isEmpty()) {
			return;
		}
		// 存在对象，再进行依赖注入处理
		// 遍历ioc中所有对象，查看对象中的字段是否有 @zhanAutowired，如果有需要维护他们的依赖注入关系
		for (Map.Entry<String, Object> entry : ioc.entrySet()) {
			// 获取bean对象中的字段信息
			Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
			for (int i = 0; i < declaredFields.length; i++) {
				Field declaredField = declaredFields[i];
				if (!declaredField.isAnnotationPresent(ShenAutowired.class)) {
					continue;
				}
				// 有注解
				ShenAutowired annotation = declaredField.getAnnotation(ShenAutowired.class);
				String beanName = annotation.value();
				if ("".equals(beanName.trim())) {
					// 没有配置具体的id，那就根据当前字段类型注入
					beanName = declaredField.getType().getName();
				}
				// 开启赋值
				declaredField.setAccessible(true);
				try {
					declaredField.set(entry.getValue(), ioc.get(beanName));
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * ioc容器
	 * 基于classNames缓存类的全限定类名，以及反射技术，完成对象的创建和管理
	 */
	private void doInstance() {
		if (classNames.size() == 0) {
			return;
		}
		try {
			for (int i = 0; i < classNames.size(); i++) {
				String className = classNames.get(i);
				// 反射
				Class<?> aClass = Class.forName(className);
				// 区分 controller,service
				if (aClass.isAnnotationPresent(ShenController.class)) {
					// controller 的 id 此处不做处理，就能类的首字母小写作为id，保存到ioc中
					String simpleName = aClass.getSimpleName();
					String lowerFirstSimpleName = lowerFirst(simpleName);
					Object o = aClass.newInstance();
					ioc.put(lowerFirstSimpleName, o);
				} else if (aClass.isAnnotationPresent(ShenService.class)) {
					ShenService annotation = aClass.getAnnotation(ShenService.class);
					// 获取注解value的值
					String beanName = annotation.value();
					// 如果指定了id，就以指定的为准
					if ("".equals(beanName.trim())) {
						beanName = lowerFirst(aClass.getSimpleName());
					}
					ioc.put(beanName, aClass.newInstance());
					// service 层往往是有接口的，面向接口开发，此时以接口名为id，放入一个对象到ioc中，便于后期根据接口类型注入
					Class<?>[] interfaces = aClass.getInterfaces();
					for (int j = 0; j < interfaces.length; j++) {
						// 以接口的全限定类名作为id放入
						ioc.put(interfaces[j].getName(), aClass.newInstance());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String lowerFirst(String str) {
		char[] chars = str.toCharArray();
		if ('A' <= chars[0] && chars[0] <= 'Z') {
			chars[0] += 32;
		}
		return String.valueOf(chars);
	}

	/**
	 * 扫描类
	 * @param scanPackage
	 */
	private void doScan(String scanPackage) {
		// 替换为磁盘路径
		String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
		File pack = new File(scanPackagePath);

		File[] files = pack.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				// 递归
				doScan(scanPackage + "." + file.getName());
			} else if (file.getName().endsWith(".class")) {
				String className = scanPackage + "." + file.getName().replaceAll(".class", "");
				classNames.add(className);
			}
		}
	}

	/**
	 * 加载配置文件
	 * @param contextConfigLocation
	 */
	private void doLoadConfig(String contextConfigLocation) {
		InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
		try {
			properties.load(resourceAsStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 处理请求：根据url找到对应的method方法进行调用处理
		String requestURI = req.getRequestURI();
		Handler handler = handlerMapping.get(requestURI);
		if (handler == null) {
			resp.getWriter().write("404 not found");
			return;
		}
		// 参数绑定,获取所有参数类型数组，数组的长度就是最后要传入的args数组长度
		Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
		// 建立新的数组
		Object[] paraValues = new Object[parameterTypes.length];
		Map<String, String[]> parameterMap = req.getParameterMap();
		// 遍历request中的所有参数（填充除了request，reponse的参数）
		for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
			String value = StringUtils.join(param.getValue(), ",");
			// 如果参数和方法中的参数匹配上了，填充数据
			if (handler.getParamIndexMapping().containsKey(param.getKey())) {
				Integer index = handler.getParamIndexMapping().get(param.getKey());
				// 把前台传过来的值填充到对应的位置
				paraValues[index] = value;
			}
		}

		int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
		int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
		paraValues[requestIndex] = req;
		paraValues[responseIndex] = resp;


		// 最终处理
		try {
			handler.getMethod().invoke(handler.getController(), paraValues);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}